/**
 * Created with Vim7.3 ubuntu12.04
 * @fileOverview : 
 * @author : Lyle <lylechen2014@gmial.com>
 * @since : 2014-08-18 14:11:33
 * @filename : static/mnm/src/views/joinus.js
 * @version : 
 * @description : 
 */
define(function(require, exports, module){

        require("{resourceUrl}css/mnm/public.css");
        require("{resourceUrl}css/mnm/share.css");
        require("{resourceUrl}css/mnm/joinus.css");

        var JoinusView, changeBool=true,tempObj={},
            $ = require('$'),
	    Backbone = require('backbone'),
            _ = require('underscore'),

            util = require('{baseSea}util/util'),
            upload = require('{baseSea}upload/upload'),
            tab = require('{baseSea}tab/zepto.tab'),
            
            lang = require('{baseSea}I18N/mnm/{locale}'),
            share = require('../share'),
            
            tpl = require('{resourceUrl}tpl/mnm/joinus.tpl'),
            tplC = require('{resourceUrl}tpl/mnm/countryList.tpl'),
            tplS = require('{resourceUrl}tpl/mnm/shengList.tpl');

        JoinusView = Backbone.View.extend({

      	        el: 'body',

		template: _.template(tpl),
		templateC: _.template(tplC),

    		initialize: function () {

                },

		render: function (obj) {
                    if ($('#joinus').length < 1) { 
		        this.renderTpl();
                        tab.init(); 
                        this.bindEvt();
		    } else {
		        $('#joinus').show();
		    }

		    if (parseInt(obj.num) > 0) {
		        tab.gotoTabs(obj.num);
		    } else {
		        tab.gotoTabs(0);
		    }
                },

                renderTpl : function() {
                    var html = this.template(lang);
                    $('body').append(html);  
                },
                     
            	events: {
                    "tap .jbc-frist"     : "handleFristData",  
                    "tap .jbc-second"    : "handleSecondData",  
                    "tap .jbc-three"     : "handleThreeData",  
                    "tap .gender_item"   : "genderToggle", 	        
                    "tap .jbb_top"       : "goSignin",        
                    "tap .jbb_bottom"    : "goServiceText" 	        
                },

                bindEvt : function() {
                     var dom = $('#joinus'),tthis = this;

                     tthis.initCountryList();
                     tthis.initUpload();

                     dom.find('.back').tap(function(){
                          tthis.goBack();
                     });
                   
                     dom.find("input[name='email']").change(function() {
                         changeBool = true;
                     });

                     dom.find("input[name='username']").change(function() {
                         changeBool = true;
                     });

                     dom.find("input[name='password']").change(function() {
                         changeBool = true;
                     });

                     $("#country").live('change',function(){
                         var val = $(this).find('option:selected').val();
                             if (parseInt(val) == 36) {
                                 tthis.ajaxShengData(val);
                             }
                     });

                },
             
                goServiceText : function() {
		     window.location.href='#termsService/whole'; 
                },
 
                goSignin : function() {
		     window.location.href='#signin/whole'; 
                },
 
                goBack : function() {
                      if (tab.info.index > 0) {
	                  window.location.href='#joinus/part/tab'+(tab.info.index-1); 
		      } else {
		          window.location.href='#index/whole'; 
		      }
                },
 
                genderToggle : function(e) {
                     var tthis = e.currentTarget;
		     $(tthis).parent().find(".gender_item").each(function(){
			 var type = $(this).attr('type');
			 $(this).removeAttr('select').removeClass('gender_item_'+type+'_select').find('div').removeClass(type+'_select').addClass(type);      
		     });
		     var type = $(tthis).attr('type');
		     $(tthis).attr('select',true).addClass('gender_item_'+type+'_select').find('div').removeClass(type).addClass(type+'_select');
                },
                
                handleFristData : function() {
                     if(parseInt($('.jbc-frist').attr('ajax')) !== 1) {
		         var bool = false, tthis=this, obj={};
			 obj.email = $("#joinus").find('input[name="email"]').val(),
			 obj.username = $("#joinus").find('input[name="userName"]').val(),
			 obj.password = $("#joinus").find('input[name="passWord"]').val();
			 bool = this.regModelValidata(obj);
			 if (bool) {
			    if ($('.jbc-frist').attr('ajax') != 1 && changeBool) {
				this.ajaxFristData(obj);
                                changeBool = false;
                                util.cloneObj(obj,tempObj);
			    } else {
				window.location.href='#joinus/part/tab1'; 
                            }
			 } else {
                            share.error('console','前端验证没通过'); 
			 }
                     }		   
		},
                  
                ajaxFristData : function(data) {
                         var dom = $('.jbc-frist');
                             dom.attr('ajax',1);
                         share.ajaxStartA(dom);
                         var tthis = this,
			     obj = {
			     url : seajs.data.vars.apiUrl+'user_account',
			     type : 'POST',
			     data : data,
			     success : function(data) {
				 if (data.error == 0 ) {
				     window.location.href='#joinus/part/tab1'; 
				 } else {
				     var obj = {};
				     switch(data.data[0].error_id) {
					 case 1:
					    obj = {bool : false, field:'userName', msg:data.data[0].msg};
					 break;
					 case 2:
					    obj = {bool : false, field:'email', msg:data.data[0].msg};
					 break;
					 case 3:
					    obj = {bool : false, field:'passWord', msg:data.data[0].msg};
					 break;
				     };
				     tthis.renderError(obj); 
				 }
			     },
			     error : function(xhr, errorType, error) {
                                 share.error('alert','user_account http request failed!'); 
			     },
                             complete : function(xhr,status){
                                 dom.attr('ajax',0);
				 share.ajaxEndA(dom);
                             } 
 
			 };
                         $.ajax(util.ajaxControl(obj));
                },
                /*
                optionVal : function(id,val) {
                      return $('#'+id).find('option[val="'+$.trim(val)+'"]').val();
                },
                */
                handleSecondData : function() {
		    var bool = false, obj = {};

		    obj.gender = $('#joinus_second').find('.gender_item[select=true]').attr('type');
		    obj.age = $("#joinus").find('input[name="age"]').val();
		    obj.r_country = $("#country option:selected").val();
                    obj.r_zip = $("#joinus").find('input[name="zipCode"]').val();

		    if (parseInt(obj.r_country) == 36) {
                        obj.r_sheng = $('#sheng option:selected').val();
                    } 

		    bool = this.regModelValidata(obj);
 		    if (bool) {
                        util.cloneObj(obj,tempObj);
                        this.ajaxSecondData(obj);
		     } 
                },               

                handleThreeData : function() {
                    var bool = false, obj = {};
		    obj.match_gender = $('#joinus_three').find('.gender_item[select=true]').attr('val');
		    obj.match_age_min = $("#joinus_three").find('#from_age option:selected').val();
		    obj.match_age_max = $("#joinus_three").find('#to_age option:selected').val();

		    bool = this.regModelValidata(obj);
 		    if (bool) {
                        util.cloneObj(obj,tempObj);
                        this.ajaxThreeData(tempObj);
		    } 
                },
              
                ajaxSecondData : function(data) {

                     var dom = $('.jbc-second');
                         dom.attr('ajax',1);
		       
		     share.ajaxStartA(dom);
		     var obj = {
			 url : seajs.data.vars.apiUrl+'user_register',
			 type : 'POST',
			 data : data,
			 success : function(data) {
				 if (data.error == 0 ) {
				     alert('reg success!');
			             window.location.href='#joinus/part/tab2'; 
				 } else {
				     alert('error');
				 } 
			 },
			 error : function(xhr, errorType, error) {
				 share.error('alert','http request failed!'); 
			 },
			 complete : function(xhr,status){
			     dom.attr('ajax',0);
			     share.ajaxEndA(dom);
			 } 
		       };
			
                       //$.ajax(util.ajaxControl(obj)); 
                },
                  
                ajaxThreeData : function(data) {
                       var dom = $('.jbc-three');
                           dom.attr('ajax',1);
		       share.ajaxStartA(dom);
                       var obj = {
			     url : seajs.data.vars.apiUrl+'user_register',
			     type : 'POST',
			     data : data,
			     success : function(data) {
				     if (data.error == 0 ) {
					 alert('reg success!');
				     } else {
					 alert('error');
				     } 
			     },
			     error : function(xhr, errorType, error) {
                                     share.error('alert','user_register http request failed!'); 
			     },
                             complete : function(xhr,status){
                                 dom.attr('ajax',0);
				 share.ajaxEndA(dom);
                             } 
		       };
			
                       $.ajax(util.ajaxControl(obj)); 
                },

                tabErrorGoto : function(obj) {
		       this.renderError(obj); 
		       //$.fn.tab.gotoTabs(1);
                },

                initUpload : function() {
		    upload.init({
		       id : 'file',
		       filter: 'image',
		       maxsize: 2048000,
		       url:seajs.data.vars.apiUrl+'basic_tmp_picture',
		       onSuccess: function(data){var data = JSON.parse(data); tempObj.img = data.url},
		       onError: function(data){console.log(data)},
		       onProgress: function(evt){
			   var width = Math.round(evt.loaded /evt.total * 100);   
			   if (width == 100) {
			       width = 0; 
			   }
			   $('#progress').css('width',width+'px');  
			},
		       onReader: function(evt){$('#img_show').html('<img src="'+evt.target.result+'" alt=""/>');} 
                     });
		},
 
                initCountryList : function() {
                      var tthis=this,
                          obj = {
				 url : seajs.data.vars.apiUrl+'basic_country_list',
				 type : 'GET',
				 success : function(data) {
				     if (data.error == 0 ) {
					 $('.r_country').html(tthis.templateC({arr:data.data}));
				     }
				 },
				 error : function(xhr, errorType, error) {
                                     share.error('alert','basic_country_list http request failed!'); 
				 } 
  		           };
                     $.ajax(util.ajaxControl(obj)); 
                },
                           
                ajaxShengData : function(val) {
                      alert('china sheng!');
                      var tthis = this,
                          obj = {
				 url : seajs.data.vars.apiUrl+'basic_country_list',
				 type : 'GET',
				 success : function(data) {
				     if (data.error == 0 ) {
					 $('.r_sheng').html(tthis.templateS({arr:data.data}));
				     }
				 },
				 error : function(xhr, errorType, error) {
                                     share.error('alert','basic_country_list http request failed!'); 
				 } 
  		           };
                      //$.ajax(util.ajaxControl(obj)); 
                },

                renderError : function(obj) {
		         var dom =  $('#joinus').find('.'+obj.field+'');
			 if (obj.field =='gender' || obj.field == 'lookForGender') {
			     if (dom.next().hasClass('err')) {
				 dom.next().remove();
			     }
			     if (!obj.bool) {
			         dom.after("<div class='err'>"+obj.msg+"</div>");
			     }
                         } else {
			     if (dom.next().hasClass('err')) {
				 dom.next().remove();
				 dom.find('input').removeAttr('style').removeClass('input_err');
				 dom.find('select').removeAttr('style').removeClass('input_err');
			     }
			     if (!obj.bool) {
				 dom.after("<div class='err'>"+obj.msg+"</div>");
				 dom.find('input').css('borderColor','#f00').addClass('input_err');
				 dom.find('select').css('borderColor','#f00').addClass('input_err');
			     }
			 }
	        },

		regModelValidata : function(model) {
		     var tthis=this,bool = true;
		     for (var x in model) {
			 (function(x,model){
			   var obj = tthis.regFieldValidata(x,model);
			       tthis.renderError(obj);
			       if (!obj.bool) {                   
				   bool = false;
			       } 
			 })(x,model);
		     }
		     return bool;
	        },

	        regFieldValidata : function(field,model) {
			var obj = {bool : true, field:field};
			switch(field) {
			   case 'email' :
				 if (model[field] == null || $.trim(model[field]) == '') { 
				     obj.bool = false;
				     obj.msg = lang.required;
				 } else if (!util.isEmail(model[field])) {
				     obj.bool = false;
				     obj.msg = lang.email_format_error;
				 }
			   break;
	     
			   case 'username': 
				 if (model[field] == null || $.trim(model[field]) == '') {
				     obj.bool = false;
				     obj.msg = lang.required;
				 } else if (!util.isLength(model[field],6,18)) {
				     obj.bool = false;
				     obj.msg = lang.username_format_error+'[6-18].';
				 }
			   break;

			   case 'password':
				 if (model[field] == null || $.trim(model[field]) == '') {
				     obj.bool = false;
				     obj.msg = lang.required;
				 } else if (!util.isLength(model[field],6,18)) {
				     obj.bool = false;
				     obj.msg = lang.password_format_error+'[6-18].';
				 }
			   break;

			   case 'match_gender':
			   case 'gender':
				if (model[field] == null || model[field] == '') {
				    obj.bool = false;
				    obj.msg = lang.selected;
				}
			   break;     
			   case 'age':
			   case 'r_country':
                           case 'r_sheng':
			   case 'r_zip':
				if (model[field] == null || model[field] == '') {
				    obj.bool = false;
				    obj.msg = lang.required;
				}                   
			   break;  
			   case 'img':
			   break;

			   case 'match_age_min' :
			   case 'match_age_max' :
				if (model[field] == null || model[field] == '') {
				    obj.bool = false;
				    obj.msg = lang.required;
				} 
                                if (field == 'match_age_max') {
				    if (model[field]<model['match_age_min']) {
					obj.bool = false;
					obj.msg = lang.joinus_lookfor_age;
				    }
				}
			   break;
			}     
			return obj;
	       },
	});
	module.exports = JoinusView;
})

